/**
 * 
 */
package com.smzd.framework.config.intercepters;

import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.smzd.utils.SessionHolder;

/**
 * @author YuZhongda
 *
 */
public class SessionMapHolderInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		System.out.println("preHandler.thread="+Thread.currentThread());
		HttpSession session = request.getSession();
		if(session!=null){
			Enumeration<?> names = session.getAttributeNames();
			while(names.hasMoreElements()){
				String name = (String)names.nextElement();
				Object value = session.getAttribute(name);
				System.out.println("SessionHolder.setObject("+name+")");
				SessionHolder.setObject(name, value);
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("postHandle.thread="+Thread.currentThread());
        Map<String, Object> map = SessionHolder.getSessionMap();
        HttpSession session = request.getSession();
        if (map != null) {
            if (session != null) {
                for (String key : map.keySet()) {
                    if (map.get(key) == null) {
                        session.removeAttribute(key);
                        System.out.println("HttpSession.remove("+key+")");
                    }else{
                        session.setAttribute(key, map.get(key));
                        System.out.println("HttpSession.set("+key+")");
                    }
                }
            }else{
                for (String key : map.keySet()) {
                    if (map.get(key) != null) {
                        if(session==null){
                            session = request.getSession(true);
                            System.out.println("HttpSession.new!!!");
                        }
                        session.setAttribute(key, map.get(key));
                        System.out.println("HttpSession.set("+key+")");
                    }
                }
            }
        }else{
            if(session!=null){
//              session.setMaxInactiveInterval(0);
                session.invalidate();
            }
        }
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("afterCompletion.thread="+Thread.currentThread());
		SessionHolder.clearObjects();
		System.out.println("SessionHolder.clearObjects!");
	}
	
}
